#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vi: ts=4 expandtab
#
# Copyright (C) 2012 KT
#
# Author: Choonho Son <choonho.son@kt.com>
#

from cloudcfg.hpc.pbs import PBS
from cloudcfg.lib.cmd_ssh import cmd_ssh
from cloudcfg.lib.cmd_nfs import cmd_nfs
from cloudcfg.lib.cmd_nis import cmd_nis
from cloudcfg.lib.cmd_tcp import cmd_tcp
from cloudcfg.lib.cmd_xen import cmd_xen
from cloudcfg.lib.cmd_account import cmd_account

from optparse import OptionParser
import traceback

__version__="1.0"

class Head(PBS):
	__cfg__ = "cfg/cloudcfg.hpc.pbs.head"
	def __init__(self, cfg={}):
		PBS.__init__(self, cfg)
		#self.updateConfig(cfg)


	def sendLog(self, me="hpc-user@ucloud.com", you='mailing.son@gmail.com', status="Pending", content='/var/log/cloudcfg.log'):
		try:
			import smtplib
			from email.MIMEText import MIMEText
			fp = open(content,'r')
			msg = MIMEText(fp.read())
			fp.close()
			msg['Subject'] = "[HPC-%s] build status" % status
			msg['From'] = me
			msg['To'] = you
			s = smtplib.SMTP()
			s.connect()
			s.sendmail(me, [you], msg.as_string())
			s.close()
			cmd = cmd_tcp(self.logger)
			c = ['cp','/dev/null',content]
			cmd.run(c)
		except:
			self.logger.debug("Failed to Send log file")
		
	def sendResult(self, msg):
		"""
		send build log for verifying
		"""
		self.sendLog(status=msg, content='/var/log/cloudcfg.log')
		self.sendLog(status='installer', content='/var/log/cloudutils.log')
		
	def qmgr(self, params):
		cmd = cmd_tcp(self.logger)
		p = params
		nodes = p['node']
		self.logger.debug("Number of Nodes:%s" % nodes)
		for node in range(int(nodes)):
			self.logger.debug("Add Node#%s" % node)
			hostname = "node%.3d" % (node+1)
			check = {'ip':hostname, 'port':15002}
			trial = cmd.checkConnection(check, trial=20,interval=30)
			if trial == False:
				self.logger.info("[## Important ##] Manually add node(%d) using qmgr" % hostname)
				continue
			cmd_str = "/opt/pbs/default/bin/qmgr -c \"create node %s\"" % hostname
			cmd.run(cmd_str, shell=True)
			

	def updateLicense(self, url):
		"""
		@param url: 6200@licenserServerIP
		
		update License Server information
		"""
		cmd_str = "/opt/pbs/default/bin/qmgr -c \"set server pbs_license_info=%s\"" % url
		self.logger.debug("Update License Info:%s" % cmd_str)
		cmd = cmd_tcp(self.logger)
		cmd.run(cmd_str, shell=True)

	def updateAA(self, domain):
		fp = open('/opt/altair/hwe/11.1/config/AA/AA_Client.properties','w')
		msg = """
java.authWsdl=%s/AAService/AuthzUserPort?wsdl
java.authEndpoint=%s/AAService/AuthzUserPort
java.adminWsdl=%s/AAService/AuthzAdminModulePort?wsdl
java.adminEndpoint=%s/AAService/AuthzAdminModulePort
java.authnWsdl=%s/AAService/AuthNPort?wsdl
java.authnEndpoint=%s/AAService/AuthNPort
#mode value can be either of the one below
# a. personal
# b. enterprise
java.mode=enterprise
java.sessionTimeout=120
java.AAVersion=PKG20120712_V11.0_RC7.4
""" % (domain, domain, domain, domain, domain, domain)
		fp.write(msg)
		fp.close()
		
	def install(self):
		try:
			self.logger.debug("Check xentools version")
			cmd = cmd_xen(self.logger)
			cmd.updateXentools()
		except:
			self.logger.debug("Failed to update Xentools")
			
		try:
			self.updateConfig(self.cfg)
			
			self.logger.debug("###########################################")
			self.logger.debug("Install HPC culster with Cluster size:%s" % self.config.getint('cluster','node'))
			self.logger.debug("###########################################")
			
		        #TODO:
			# if automation, config account is not needed
			self.logger.debug("##################")
			self.logger.debug("Config account")
			self.logger.debug("##################")
			cmd = cmd_account(self.logger)
			params = self.getSectionParams('account')
			cmd.useradd(params)

		
			self.logger.debug("##################")
			self.logger.debug("Config SSH")
			self.logger.debug("##################")
			cmd = cmd_ssh(self.logger)
			params = self.getSectionParams('ssh')
			p = params
		        #Key generation	
			cmd.ssh_keygen(params)
			cmd.add2authorized_keys(params['public_key'],params['authorized_keys'])
			cmd.chown(p['path'], p['account'],p['group'])
			cmd.chown(p['public_key'], p['account'],p['group'])
			cmd.chown(p['authorized_keys'], p['account'],p['group'])
		except:
			self.logger.debug(out=traceback.format_exc())
			self.sendResult("SSH\n%s"%out)

		try:
			self.logger.debug("##################")		
			self.logger.debug("Config NFS Server")
			self.logger.debug("##################")
			params = self.getSectionParams('nfs')
			cmd = cmd_nfs(self.logger)
			cmd.create_volume(params)
			params = {}
			params['path'] = self.config.get('nfs','temp_export')
			cmd.update_export(params)
			params = {}
			params['path'] = self.config.get('nfs','base_export')
			cmd.update_export(params)
			
			cmd.service('nfs','restart')
			cmd.addService('nfs')

		except:
			self.logger.debug(out=traceback.format_exc())
			self.sendResult("NFS\n%s" % out)

		try:
		        self.logger.debug("######################")		
			self.logger.debug("Configure NIS Server")
			self.logger.debug("######################")				
		        #clean up, template garbage
			cmd.rm('/var/yp/nicknames')
			cmd.rm('/var/yp/ypservers')
			cmd.rmdir('/var/yp/binding/')
			cmd.rmdir('/var/yp/cs82epc-dev.ucloud.com')
			
			params = self.getSectionParams('nis')
			params['NISDOMAIN'] = self.config.get('common','domain')
			
			cmd = cmd_nis(self.logger)
			cmd.installPackage(params['package'])
			cmd.updateHostOrder(params)
			cmd.updateNISDOMAIN(params)
			cmd.updateYPCONF(params)
			cmd.updateNsswitch()
			
			self.logger.debug("Start ypserv")
			cmd.service('ypserv','restart')
			cmd.addService('ypserv')
			self.logger.debug("Start yppasswdd")
			cmd.service('yppasswdd','restart')
			cmd.addService('yppasswdd')
			cmd.updateDB(params)
			self.logger.debug("Start ypbind")
			cmd.service('ypbind','restart')
			cmd.addService('ypbind')
		except:
			self.logger.debug(out=traceback.format_exc())
			self.sendResult("NIS\n%s" % out)

		try:
			# automatic with PBS
			self.logger.debug("Configure PBS Pro")
			params = self.getSectionParams('cluster')
			#url = '6200@14.63.252.33'
			url = '6200@14.63.254.62:6200@14.63.254.63:6200@14.63.254.64'
			self.logger.debug("Update License Info")
			self.updateLicense(url)
			self.logger.debug("Update qmgr")
			self.qmgr(params)
		except:
			self.logger.debug(out=traceback.format_exc())
			self.sendResult("PBS\n%s" % out)

		try:
			
			self.logger.debug("Update hwportal license")
			if cmd.isExist('/opt/altair/hwe/11.1/binaries/framework/data/adminSettings.xml'):
				#update hweportal license
				self.logger.debug("Update hweportal license info")
				cmd_string = ['rm', '-f', '/opt/altair/hwe/11.1/binaries/framework/data/adminSettings.xml']
				cmd.run(cmd_string)
				cmd_string = ['wget','http://14.63.252.33/adminSettings.xml','-O','/opt/altair/hwe/11.1/binaries/framework/data/adminSettings.xml']
				cmd.run(cmd_string)

				domain = self.config.get('common','domain')
				full_domain = "http://head1.%s:8086/hwe" % domain
				self.logger.debug("Full Domain:%s" % full_domain)

				self.updateAA(full_domain)
				#self.logger.debug("Stopping hweportal")
				#cmd.service('hweportal','stop')
				#self.logger.debug("Starting hweportal")
				#cmd.service('hweportal','start')
		except:
			self.logger.debug("Failed in CM")
			traceback.format_exc()
			self.sendResult("CM")
			

		return self.sendResult("Success")

def install(cfg):
	inst = Head(cfg)
	inst.install()

if __name__ == "__main__":
	install({})
